<script lang="ts" setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import treeSelect from '@/components/tree-select-edl/treeSelect.vue'
import type { FormInstance, FormRules } from 'element-plus'
import xtpzService from '@/api/xtpz'
import TreeUtilDTO from '@/utils/tree'
import { AjglgxAddInputDTO } from '@/api/xtpz-dto'
import { getFldm } from '@/utils/get-fldm'
// 入参
const emit = defineEmits(['refresh'])
// 生命周期
onMounted(() => {
  // 获取案卷类别
  getAjuanlb()
  // 获取案件类别
  getAjlb()
})
/*
 * 打开弹框
 */
//
const loading = ref<boolean>(false)
const dialogVisible = ref<boolean>(false)
const openDialog = () => {
  dialogVisible.value = true
  resetField()
}

/*
 * 获取案卷类别
 */
const ajlxList = ref<any[]>([])
const getAjuanlb = async () => {
  ajlxList.value = await getFldm('gd024')
}

/*
 * 获取案件类别
 */
const ajlbList = ref<any[]>([])
const ajlbData = ref<any[]>([])
const getAjlb = async () => {
  xtpzService
    .queryAjlblb()
    .then((res) => {
      if (res) {
        ajlbData.value = res.data
        ajlbList.value = TreeUtilDTO.getTreeData(res.data || [], 'dm', 'fdm')
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/*
 * 验证表单
 */
const ruleForm = ref<AjglgxAddInputDTO>({
  ajlxbm: '',
  ajlxmc: '',
  ajlbbm: [],
  ajlbmc: [],
})
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<any>>({
  ajlxbm: [{ required: true, message: '必填', trigger: 'change' }],
  ajlbbm: [{ required: true, message: '必填', trigger: 'change' }],
})
const validateForm = () => {
  ruleFormRef.value?.validate((valid) => {
    if (valid) {
      saveData()
    }
  })
}
// 重置表单
const resetField = () => {
  nextTick(() => {
    ruleFormRef.value!.resetFields()
  })
}

/*
 * 保存数据
 */
const saveData = () => {
  if (newListArr.value.length <= 0) {
    return ElMessage({ type: 'warning', message: '请选择案件类别' })
  }
  const params = {
    ajlxbm: ruleForm.value.ajlxbm,
    ajlxmc: ruleForm.value.ajlxmc,
    glxxList: newListArr.value.map((el: any) => {
      return {
        ajlbbm: el.dm,
        ajlbmc: el.mc,
      }
    }),
  }
  loading.value = true
  xtpzService
    .addAjglgx(params)
    .then(() => {
      ElMessage.success('保存成功')
      emit('refresh')
      dialogVisible.value = false
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 案卷类别树点击
 */
const nodeAjlbChange = (val: string, node: any, mc: string) => {
  const form = ruleForm.value as any
  form[mc] = node?.mc
}

/**
 * 案件类别树点击
 */

const newListArr = ref([])
const nodeChange = (data: any, node: any) => {
  if (node && node.length > 0) {
    const nodeTemp = node?.filter((item: any) => item.fdm !== '-1')
    newListArr.value = nodeTemp
  }
  ruleForm.value.ajlbbm = data
}

defineExpose({ openDialog })
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加归档范围配置"
    width="600px"
    :close-on-click-modal="false"
  >
    <div class="dialog-box">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="90px" status-icon>
        <el-form-item label="案卷类别" prop="ajlxbm">
          <tree-select
            v-model="ruleForm.ajlxbm"
            nodeKey="dm"
            :options="ajlxList"
            clearable
            @node-change="(data:string, node:any)=> nodeAjlbChange(data, node,'ajlxmc')"
          />
        </el-form-item>
        <el-form-item label="案件类别" prop="ajlbbm">
          <!-- @node-change="(data:string, node:any)=> nodeChange(data, node,'ajlbmc')" -->
          <tree-select
            v-model="ruleForm.ajlbbm"
            nodeKey="dm"
            multiple
            :options="ajlbList"
            clearable
            showAllSelection
            showCurrentButton
            :isLeafNode="false"
            :treeProps="{
              children: 'children',
              label: 'mc',
            }"
            :checkStrictly="false"
            @nodeChange="nodeChange"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="validateForm" :loading="loading">确定</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
}
</style>
